package com.hdp.jetpack_mvvm.livedata

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.hdp.jetpack_mvvm.R
import kotlinx.android.synthetic.main.activity_view_model1.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LiveDataActivity2 : AppCompatActivity() {
    val TAG = "ViewModelActivity2"
    private lateinit var mViewModel1: ViewModel1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_model2)
        init()
    }

    fun init() {
        //全局的LiveData
        SingletonLiveData.getName().observe(this, {
            edit_name_global.setText(it)
        })
        mViewModel1 = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        ).get(ViewModel1::class.java)
        Log.e(TAG, mViewModel1.toString())
        //用户名
        mViewModel1.getName().observe(this, { name ->
            edit_name.setText(name)
        })
        //密码
        mViewModel1.getPwd().observe(this, { pwd ->
            edit_pwd.setText(pwd)
        })
        //提交按钮
        mViewModel1.getCanSubmit().observe(this, { enable ->
            btn_submit.isEnabled = enable
        })


        mockLoadData()
    }

    private fun mockLoadData() {
        GlobalScope.launch(Dispatchers.Main) {
            delay(1000)
            mViewModel1.loadName2()
            delay(1000)
            //更新全局LiveData
            SingletonLiveData.setName("王五")
        }
    }
}